package src.dp.sequence;

public class no583 {//两个字符串的删除操作

    //法1：先求出最长公共子序列，再用两个串减去公共序列，即为操作步数
    public int minDistance(String word1, String word2) {

        int len1 = word1.length();
        int len2 = word2.length();
        int[][] dp = new int[len1 + 1][len2 + 1];

        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                //i、j遍历时，比较的是i-1 和 j-1 位置的字母
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    //当前元素不相等时，就维护之前的最大状态
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        int commonSequence = dp[len1][len2];
        return len1 + len2 - 2 * commonSequence;

    }

    //法2：不同的子序列问题中，两个串都能减
    public int minDistance2(String word1, String word2) {
        int len1 = word1.length();
        int len2 = word2.length();
        int[][] dp = new int[len1 + 1][len2 + 1];

        //word2为空串时，只需word1有几个字母就删几步，就把word1也变为空串
        for (int i = 0; i <= len1; i++) dp[i][0] = i;

        //word1为空串，把word2都删去
        for (int j = 0; j <= len2; j++) dp[0][j] = j;


        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    //不相同时，分3种：两个都删；删word1中的；删word2中的
                    dp[i][j] = Math.min(dp[i - 1][j - 1] + 2,
                            Math.min(dp[i - 1][j]+1, dp[i][j - 1]+1) );
                }
            }
        }
        return dp[len1][len2];
    }

}
